const multer = require('multer');
const path = require('path');
const fs = require('fs');
const ApiError = require('./ApiError');
const httpStatus = require('http-status');

// 确保上传目录存在
const createUploadDir = (dir) => {
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
};

// 配置头像上传存储
const avatarStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadDir = path.join(process.cwd(), 'public/uploads/avatars');
    createUploadDir(uploadDir);
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    // 使用用户ID和时间戳命名，保留原始扩展名
    const userId = req.user.id;
    const timestamp = Date.now();
    const fileExt = path.extname(file.originalname).toLowerCase();
    cb(null, `avatar-${userId}-${timestamp}${fileExt}`);
  }
});

// 文件过滤器，只允许图片
const imageFilter = (req, file, cb) => {
  // 检查文件MIME类型
  if (!file.mimetype.startsWith('image/')) {
    return cb(new ApiError(httpStatus.BAD_REQUEST, '只能上传图片文件'), false);
  }
  
  // 检查扩展名
  const allowedExt = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
  const fileExt = path.extname(file.originalname).toLowerCase();
  if (!allowedExt.includes(fileExt)) {
    return cb(
      new ApiError(
        httpStatus.BAD_REQUEST, 
        `不支持的文件类型，允许的类型: ${allowedExt.join(', ')}`
      ), 
      false
    );
  }
  
  cb(null, true);
};

// 头像上传配置
const avatarUpload = multer({
  storage: avatarStorage,
  fileFilter: imageFilter,
  limits: {
    fileSize: 5 * 1024 * 1024 // 限制5MB
  }
});

module.exports = {
  avatarUpload
}; 